package com.spring.lo.framework.factory.xml;

import com.spring.lo.framework.core.io.ClassPathResource;
import com.spring.lo.framework.core.io.Resource;
import com.spring.lo.framework.factory.support.BeanDefinitionReader;
import com.spring.lo.framework.factory.support.BeanDefinitionRegistry;
import com.spring.lo.framework.util.DocumentUtils;
import org.dom4j.Document;

import java.io.IOException;

/**
 * 读取XML文件进行BeanDefinition的加载
 * @author zhangbh
 * 2023-05-29 07:50
 **/
public class XMLBeanDefinitionReader implements BeanDefinitionReader {


    private BeanDefinitionRegistry beanDefinitionRegistry;

    public XMLBeanDefinitionReader(BeanDefinitionRegistry beanDefinitionRegistry) {
        this.beanDefinitionRegistry = beanDefinitionRegistry;
    }

    @Override
    public void loadBeanDefinitions(Resource resource) {
        Document document;
        try {
            document = DocumentUtils.createDocument(resource.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(" document 解析异常", e);
        }
        BeanDefinitionDocumentReader documentReader = new DefaultBeanDefinitionDocumentReader(beanDefinitionRegistry);

        documentReader.registerBeanDefinitions(document);
    }

    @Override
    public void loadBeanDefinitions(String location) {
        Resource resource = new ClassPathResource(location);
        loadBeanDefinitions(resource);
    }
}
